let _WalletApi_signAndPay_Data = {};
async function sendTx2(tokenSymbol, signHash) {
  let { result, msg, data } = await $http.post("plugin.love-speed-pool.frontend.wallet-pay.send-transaction",{param: {
    'tokenSymbol': tokenSymbol,
    'hexString': signHash,
  }},".");
  if (result == 0) return alert(msg);
  if (result == 1 && data.code != 0) {
    window.__lendApp__.$dialog.alert({
      title: '提示',
      message: "交易失败:" + data.msg,
    }).then(() => {});

  }else {
    walletPaySuccess(data.data);
  }
  window.__lendApp__.isclick = false;
}
async function walletPaySuccess(hash) {
  let { result, msg, data } = await $http.get("plugin.love-speed-pool.frontend.wallet-pay.pay",{
    order_pay_id:_WalletApi_signAndPay_Data.order_pay_id,
    tokenSymbol:_WalletApi_signAndPay_Data.tokenSymbol,
    txHash: hash,
    wallet_site: _WalletApi_signAndPay_Data.toAddress
  },".");
  if (result == 0) return alert(msg);
  if (result == 1 && data.code == 0) {
    window.__lendApp__.$dialog.alert({
      title: '提示',
      message: '钱包交易成功，为您查询订单状态',
    }).then(() => {});
    // window.__lendApp__ 为this
    window.__lendApp__.$router.push(window.__lendApp__.fun.getUrl("payBack", {ids: _WalletApi_signAndPay_Data.order_pay_id}));
  }
}


// 统一代扣支付
async function signAndPay(_info) {
  _WalletApi_signAndPay_Data = _info;
  const tokenName = _info.tokenSymbol;
  if(!tokenName){
    alert('请输入代币名称');
    window.__lendApp__.isclick = false;
    return;
  }
  if(!_WalletApi_signAndPay_Data.exer) {
    alert('商户未开通钱包支付');
    window.__lendApp__.isclick = false;
    return;
  }

  let { result, msg, data } = await $http.post("plugin.love-speed-pool.frontend.wallet-pay.create-raw-transaction",{param: {
    "tokenSymbol": tokenName,
    "amount": parseInt(_info.amount*100000000),
    "toAddress":  _info.toAddress
  }},".");

  if (result == 0) return alert(msg);
  if (result == 1 && data.code == 0) {
    signTxGroup2(data.data, _WalletApi_signAndPay_Data.exer, function (v) {
      if (v.error) {
        window.__lendApp__.$dialog.alert({
          title: '提示',
          message: JSON.stringify(v),
        }).then(() => {});
        // alert(JSON.stringify(v));
        window.__lendApp__.isclick = false;
      } else {
        sendTx2(tokenName, v.signHash);
      }
    });
  } else {
    window.__lendApp__.$dialog.alert({
      title: '警告',
      message: JSON.stringify(data),
    }).then(() => {});
    window.__lendApp__.isclick = false;
    console.log("构造签名交易失败", data);
  }
}

function signTxGroup2(createHash, exer, callback) {
  jsBridge.signTxGroup({
    cointype: "BTY",
    createHash: createHash,
    exer: exer + '.token',
    withhold: _WalletApi_signAndPay_Data.withhold,//1:代付 -1不代付
  },(v)=>{
    callback(JSON.parse(v));
  });
}


export { signAndPay };